/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javamail.common.logAllLevels;

/**
 *
 * @author sriram
 */
public class config {
    private Properties prop = null;
    private Properties dflt = null;
    private boolean noConfig = false;
    private String configFile = null;
    private String defaultConfig = "sipspeaker.cfg";
    private static Logger logger = logAllLevels.getLogger();

    /*public config() {
        // Set logger level here. Choose upto which level logs are required
        logger.setLevel(Level.INFO);
        logger.finest("Entering config::config()");
        prop = new Properties(getDefaultProperties());
        loadConfigFile(defaultConfig);
        logger.finest("Exiting config::config()");
    }*/

    public config(cliParms cliparms) {
        // Set logger level here. Choose upto which level logs are required
        logger.setLevel(Level.INFO);
        logger.finest("Entering config::config()");
        prop = new Properties(getDefaultProperties());
        //prop = getDefaultProperties();
        loadCLIParameters(cliparms);
        if(noConfig)
            storeDefaultProperties();
        logger.finest("Exiting config::config()");
    }
    
    /*public config(String name) {
        // Set logger level here. Choose upto which level logs are required
        logger.setLevel(Level.INFO);
        logger.finest("Entering config::config(name)");
        prop = new Properties(getDefaultProperties());
        loadConfigFile(name);
        logger.finest("Exiting config::config(name)");
    }*/
    
    private void loadCLIParameters(cliParms cliparms) {
        if(cliparms.config_file_name!=null)
            loadConfigFile(cliparms.config_file_name);
        else
            loadConfigFile(defaultConfig);
        if(cliparms.http_bind_address!=null) {
            String[] http = cliparms.http_bind_address.split(":");
            if(http.length == 2) {
                prop.setProperty("http_interface", http[0]);
                prop.setProperty("http_port", http[1]);
            }
        }
        if(cliparms.sip_uri!=null) {
            String[] sip = cliparms.sip_uri.split("@");
            if(sip.length==2) {
                String[] sipAddress = sip[1].split(":");
                if(sipAddress.length ==2) {
                    prop.setProperty("sip_user", sip[0]);
                    prop.setProperty("sip_interface", sipAddress[0]);
                    prop.setProperty("sip_port", sipAddress[1]);
                }
            }
        }
    }
    
    private void loadConfigFile(String name) {
        logger.finest("Entering config::load");
        try {
            configFile = new String(name);
            prop.load(new FileInputStream(name));
            logger.info("Using "+ name + " as config file");
        } catch (FileNotFoundException e) {
            logger.warning("Config file not found!");
            logger.warning("Using default configuration");
            noConfig = true;
        } catch (IOException e) {
            // Clear up the properties in prop.
            // It might be corrupted, hence load default configuration
            logger.warning("Unspecified error occured!");
            logger.warning("Using default configuration");
        }
        logger.fine("Exiting config::load");
    }
    
    private void loadAllNonDefaultValues(Properties fProp) {
        if(prop==null || fProp==null) {
            logger.warning("Prop null, create one first!");
            return;
        }
        if(fProp.getProperty("default_message")!=null) {
            prop.setProperty("default_message",fProp.getProperty("default_message"));
        }
        if(fProp.getProperty("message_wav")!=null) {
            prop.setProperty("message_wav",fProp.getProperty("message_wav"));
        }
        if(fProp.getProperty("message_text")!=null) {
            prop.setProperty("message_text",fProp.getProperty("message_text"));
        }
        if(fProp.getProperty("message_received")!=null) {
            prop.setProperty("message_received",fProp.getProperty("message_received"));
        }
        if(fProp.getProperty("sip_interface")!=null) {
            prop.setProperty("sip_interface",fProp.getProperty("sip_interface"));
        }
        if(fProp.getProperty("sip_port")!=null) {
            prop.setProperty("sip_port",fProp.getProperty("sip_port"));
        }
        if(fProp.getProperty("sip_user")!=null) {
            prop.setProperty("sip_user",fProp.getProperty("sip_user"));
        }
        if(fProp.getProperty("http_interface")!=null) {
            prop.setProperty("http_interface",fProp.getProperty("http_interface"));
        }
        if(fProp.getProperty("http_port")!=null) {
            prop.setProperty("http_port",fProp.getProperty("http_port"));
        }
    }

    private Properties getDefaultProperties() {
        dflt = new Properties();
        // Set the default values for the configuration
        dflt.setProperty("default_message", "default.wav");
        dflt.setProperty("message_wav", "currentmessage.wav");
        dflt.setProperty("message_text", "Welcome to the java speech server. You have no messages now!");
        dflt.setProperty("message_received", "0");
        dflt.setProperty("sip_interface", "0.0.0.0");
        dflt.setProperty("sip_port", "5600");
        dflt.setProperty("sip_user", "sriram");
        dflt.setProperty("http_interface", "127.0.0.1");
        dflt.setProperty("http_port", "8080");
        return dflt;
    }
    
    private String getProperty(String property) {
        String result = prop.getProperty(property.trim());
        logger.finer(property + ": " + result);
        return result;
    }
    
    public String getDefaultMessage() {
        return getProperty("default_message");
    }
    
    public String getCurrentMessage() {
        return getProperty("message_wav");
    }

    public String getMessageText() {
        return getProperty("message_text");
    }

    public String getMessageRcvd() {
        return getProperty("message_received");
    }

    public String getSipInterface() {
        return getProperty("sip_interface");
    }

    public int getSipPort() {
        String port = getProperty("sip_port");
        try {
            return Integer.parseInt(port.trim());
        } catch(NumberFormatException e) {
            logger.warning("sip_port field in configuration file is not integer!"+port);
            return 5060;
        }
    }

    public String getSipUser() {
        return getProperty("sip_user");
    }

    public int getHttpPort() {
        String port = getProperty("http_port");
        try {
            return Integer.parseInt(port.trim());
        } catch (NumberFormatException e) {
            logger.warning("http_port field in configuration file is not integer!"+port);
            return 8080;
        }
    }

    public String getHttpInterface() {
        return getProperty("http_interface");
    }

    private void setProperty(String name, String value) {
        if(name!=null && value!=null)
            prop.setProperty(name, value);
        storeProperties();
    }
    
    public void setMessageText(String value){
        setProperty("message_text", value);
    }
    
    public void setMessageReceived(Date date){
        int time = (int)date.getTime()/1000;
        setProperty("message_received", ""+time);
    }
    
    public void deleteProperty(String name) {
        try {
            if(name!=null)
                prop.setProperty(name, dflt.getProperty(name));
            storeProperties();
        } catch (Exception ignored) { }
    }
    
    public void deleteMessageText(){
        deleteProperty("message_text");
    }
    
    public void storeProperties() {
        try {
            if(configFile!=null)
                prop.store(new FileOutputStream(configFile), "WebStore");
        } catch(IOException ignored) { }
    }
    public void storeDefaultProperties() {
        try {
            if(configFile!=null && noConfig == true) {
                File newFile = new File(configFile);
                logger.info("Creating Configuration file with default values");
                if(!newFile.exists())
                    newFile.createNewFile();
                dflt = getDefaultProperties();
                dflt.store(new FileOutputStream(configFile), "WebStore");
            }
        } catch(Exception ignored) {}
    }
}
